﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace EpiMapit
{
    public class PieUrlGenerator
    {

        public PieUrlGenerator()
        {
        }

        public static string GetPieChartUrl(int width, int height, CaseSet caseSet)
        {
            var values = caseSet.Levels.Where(x => x.Value > 0);

            var urlformat = "http://chart.apis.google.com/chart?cht=p&chs={0}x{1}&chd=t:";

            string result;
			float total = caseSet.TotalSize();

            //I add the values, discarding values <= 0
            if (values.Count() > 0)
            {
                var resultBuilder = values.Skip(1).Aggregate(
                    new StringBuilder().AppendFormat(urlformat, width, height).Append(values.First().Value),
                    (sb, item) => sb.AppendFormat(",{0}", item.Value));

                //With &chdl= I will add labels to each pie portion, discarding values <= 0
                resultBuilder.Append("&chdl=");

                values.Skip(1).Aggregate(resultBuilder.AppendFormat("{0} : {1}",values.First().Key, values.First().Value),
                    (sb, item) => sb.AppendFormat("|{0} : {1}", item.Key, item.Value));

                //I add scaling to avoid not taking into account values > 100
                int maxValue = caseSet.Levels.Values.Max();
                resultBuilder.AppendFormat("&chds=0,{0}",maxValue);

				resultBuilder.Append("&chco=");
				
				AppendColor(resultBuilder, ControlConstants.InnerRingColor).Append(",");
				AppendColor(resultBuilder, ControlConstants.FirstRingColor).Append(",");
				AppendColor(resultBuilder, ControlConstants.SecondRingColor).Append(",");
				AppendColor(resultBuilder, ControlConstants.ThirdRingColor);

				result = resultBuilder.ToString();
            }
            else
            {
                result = new StringBuilder().AppendFormat(urlformat, width, height).ToString();
            }
            
            return result;
        }

		private static StringBuilder AppendColor(StringBuilder builder, Color color)
		{
			builder.AppendFormat("{0:X2}{1:X2}{2:X2}", color.R, color.G, color.B);
			return builder;
		}
    }
}
